import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:management/const/consts.dart';
import 'package:management/data/network/api/api.dart';
import 'package:management/data/network/entity/project/response/ListProjectResponse.dart';
import 'package:management/element/loading.dart';
import 'package:management/element/showLogSheet.dart';
import 'package:management/element/toast.dart';
import 'package:management/main.dart';

import 'state.dart';

class MainScreenLogic extends GetxController {
  final MainScreenState state = MainScreenState();

  Future<void> refreshMainPage() async {
    LoadingElement.loadingDialog(true);
    _initData(true);
  }

  @override
  void onInit() {
    super.onInit();
    _initData(false);
  }

  void _initData(bool isRefresh) async {
    await MyHttpClient.getWorkLoadType().then((value) {
      if (value.code == 200) {
        state.workLoadType = value.data!.workloadType!;
      } else {
        Utils.toastError(value.msg);
        return;
      }
    }).onError((error, p) {
      Utils.toastError(error);
      return;
    });
    await MyHttpClient.getMyProject(null, null, null, null, null).then((value) {
      if (value.code == 200) {
        state.listRecentFinishProject.clear();
        var now = DateTime.now();
        value.data?.records?.forEach((element) {
          var endTime =
              DateTime.parse(element.endTime ?? "2001-03-18 06:18:43");
          var differ = endTime.difference(now);
          if (differ.inDays < 90 && differ.inDays >= 0) {
            state.listRecentFinishProject.add(element);
          }
          state.listRecentFinishProject.refresh();
          if (isRefresh) Get.back();
        });
      } else {
        Utils.toastError(value.msg);
        return;
      }
    }).onError((error, p) {
      Utils.toastError(error);
      return;
    });
    await MyHttpClient.getListDemandOrTaskForMain(null, null, null)
        .then((value) {
      if (value.code == 200) {
        if (value.data?.total != 0) {
          state.listChildDemand.value = value.data!.records!;
        }
      } else {
        Utils.toastError(value.msg);
        return;
      }
    }).onError((error, p) {
      Utils.toastError(error);
      return;
    });
  }

  void jumpToUploadWorkScreen() => Get.toNamed(RouteConfig.uploadWorkLogScreen);

  jumpToMainSearch() {}

  jumpToProjectDetail(Records listProject) {
    Get.toNamed(RouteConfig.projectDetailScreen,
        arguments: {'projectId': listProject.id, 'pid': 0});
  }

  getBg(listProject) {
    if (listProject == null) {
      return AssetImage(state.listBg[Random().nextInt(99) % 4]);
    }
    if (listProject.backgroundUrl == null ||
        listProject.backgroundUrl!.isEmpty) {
      return AssetImage(state.listBg[listProject.id!.toInt() % 4]);
    }
    return NetworkImage(listProject.backgroundUrl!);
  }

  getLogo(listProject) {
    if (listProject == null) {
      return AssetImage(state.listBg[Random().nextInt(99) % 4]);
    }
    if (listProject.logoUrl == null || listProject.logoUrl!.isEmpty) {
      return AssetImage(state.listBg[(listProject.id!.toInt() + 1) % 4]);
    }
    return NetworkImage(listProject.backgroundUrl!);
  }

  Color getMainColor(Records? listProject) {
    if (listProject == null) {
      return state.listColor[0];
    }
    var index = listProject.id?.toInt() ?? 0;
    return state.listColor[index % 4];
  }

  String getFinishDay(listProject) {
    if (listProject == null) {
      return MyText.xDayLeft.trParams({'x': '0'});
    }
    var now = DateTime.now();
    var end = DateTime.parse(listProject.endTime ?? "2001-03-18 06:18:43");
    if (now.isAfter(end)) {
      return MyText.xDayLeft.trParams({'x': '0'});
    }
    var difference = end.difference(now);
    return MyText.xDayLeft.trParams({'x': difference.inDays.toString()});
  }

  double getProgress(Records? listProject) {
    if (listProject == null) {
      return 0;
    }
    if (listProject.totalDemand == null || listProject.finishDemand == null) {
      return 1;
    }
    if (listProject.totalDemand == 0) {
      return 0;
    }
    return listProject.finishDemand! / listProject.totalDemand!;
  }

  void jumpToNextDemand(num? id) {
    if (id == null) {
      return;
    }
    Get.toNamed(RouteConfig.demandOrTaskScreen,
        preventDuplicates: false, arguments: {'demandId': id});
  }

  void changePriority() {}

  getFlagPriorityColor(num? priority) {
    if (priority == null) return Colors.transparent;
    switch (priority.toInt()) {
      case 0:
        return MyColor.grayScale[200];
      case 1:
        return MyColor.lightBlue;
      case 2:
        return MyColor.lightGreen;
      case 3:
        return MyColor.red;
    }
    return Colors.transparent;
  }

  seeDemandLog(num? id) {
    if (id == null) return;
    MyLogSheet.showLogSheet(id);
  }

  void getListByStatus() {
    LoadingElement.loadingDialog(true);
    MyHttpClient.getListDemandOrTaskForMain(
            null,
            state.selectValue.value == -1
                ? null
                : state.selectValue.value.toString(),
            null)
        .then((value) {
      if (value.code == 200) {
        state.listChildDemand.clear();
        if (value.data?.total != 0) {
          state.listChildDemand.value = value.data!.records!;
          state.listChildDemand.refresh();
        }
        Get.back();
      } else {
        Utils.toastError(value.msg);
        return;
      }
    }).onError((error, p) {
      Utils.toastError(error);
      return;
    });
  }
}
